//
//  FriendList.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift


class FriendList: UIViewController, UITableViewDataSource, UITableViewDelegate, HttpProtocol{
    
    @IBOutlet weak var FriendListTable: UITableView!
    var eHttp:HTTPController = HTTPController()
    
    var Friends = [Friend]()
    var tableData:[JSON]=[]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBarController!.tabBar.hidden = false;
        print("haohaodedede")
        self.initView()
        //在这里进行请求
        self.isLogin()
        
    }
    
    func isLogin() {
        let keychain = KeychainSwift(keyPrefix: "myTestKey_")
        
        if((keychain.get("QCDTUSERNAME") == nil) || (keychain.get("QCDTUSEPASSWD") == nil)) {
            //跳转到注册页面--这里需要切换rootview
            let secondStoryBoard = UIStoryboard.init(name: "Login", bundle: nil)
        
            let toLogin = secondStoryBoard.instantiateViewControllerWithIdentifier("LoginCon")
            //self.navigationController?.navigationBarHidden = true;
            //self.tabBarController!.tabBar.hidden = true;
            //self.navigationController?.pushViewController(toLogin, animated: true)
            //self.navigationController?.presentViewController(toLogin, animated: true, completion: { () -> Void in
             //   return
            //})
            
            var window:UIWindow = UIApplication.sharedApplication().keyWindow!
            window.rootViewController = toLogin
            window.makeKeyAndVisible()
        }else {
            
            self.navigationController?.navigationBarHidden = false;
            self.tabBarController!.tabBar.hidden = false;
            
            /*
            
            let urladdress = "http://42.62.18.210:8090/apiradio/ar/autoLogin?plateNumber="+keychain.get("QCDTUSERNAME")!+"&password="+keychain.get("QCDTUSEPASSWD")!+"&deviceID="+keychain.get("QCDTSEVERUUID")!+"&lng="+"&lat"
            print(urladdress)
            Alamofire.request(.GET, urladdress)
                .responseJSON { response in
                    
                    if let result = response.result.value {
                        //print("JSON: \(JSON)")
                        let json = JSON(result)
                    }
            }*/
            
            //请求好友列表
            /*
            let urladdress = "http://42.62.18.210:8090/apiradio/ar/getFriends?userID="+keychain.get("registerUserID")!
            print(urladdress)
            Alamofire.request(.GET, urladdress)
                .responseJSON { response in
                    if let result = response.result.value {
                        print("JSON: \(result)")
                        let json = JSON(result)
                        if String(json["msg"]) == "607" {
                            //没有好友或者出错
                            //提示没有好友让其去添加好友
                        }else {
                            //给好友列表添加值
                            if let channels = json["obj"].array {
                                print(channels)
                                self.tableData = channels
                                
                                for var i = 0; i < self.tableData.count; i++
                                {
                                    let rowData:JSON = self.tableData[i]
                                    // print(rowData["channelName"].string)
                                    //streets.append(Street(StreetName: "未知", MsgNum: String(rowData["count"])))
                                    self.Friends.append(Friend(PlatNumber: String(rowData["plateNumber"]), PortailUrl: String(rowData["headerPath"]), MsgText: "要不是你,我就信了", TimeText: "昨天", MessageNum: "10"))
                                }
                                
                                self.FriendListTable!.reloadData()
                            }
                        }
                        
                    }
            }
            
            */
        }
    }
    
    func initView() {
        FriendListTable.dataSource = self
        FriendListTable.delegate   = self
        eHttp.delegate = self
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /* 获取数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        //print("results: \(results)")
        let json = JSON(results)
        
        if let channels = json["obj"].array {
            
            print(channels)

        }
    }
    
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "FriendCell"
        
        var cell: FriendListModel! = tableView.dequeueReusableCellWithIdentifier(identifier) as? FriendListModel

        if cell == nil {
            cell = FriendListModel(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(Friends[indexPath.row])
        
        return cell!
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Friends.count
    }
    

    override func viewWillAppear(animated: Bool) {
        //先清空
        self.Friends.removeAll()
        
        //请求好友列表
        let keychain = KeychainSwift(keyPrefix: "myTestKey_")
        if keychain.get("registerUserID") == nil {
            return;
        }
        
        let urladdress = "http://42.62.18.210:8090/apiradio/ar/getFriends?userID="+keychain.get("registerUserID")!
        print(urladdress)
        Alamofire.request(.GET, urladdress)
            .responseJSON { response in
                if let result = response.result.value {
                    print("JSON: \(result)")
                    let json = JSON(result)
                    if String(json["msg"]) == "607" {
                        self.Friends.removeAll()
                        //没有好友或者出错
                        //提示没有好友让其去添加好友
                    }else {
                        //给好友列表添加值
                        if let channels = json["obj"].array {
                            print(channels)
                            self.tableData = channels
                            
                            for var i = 0; i < self.tableData.count; i++
                            {
                                let rowData:JSON = self.tableData[i]
                                // print(rowData["channelName"].string)
                                //streets.append(Street(StreetName: "未知", MsgNum: String(rowData["count"])))
                                //self.Friends.append(Friend(PlatNumber: String(rowData["plateNumber"]), PortailUrl: String(rowData["headerPath"]), MsgText: "我们成为了好友"))
                                self.Friends.append(Friend(PlatNumber: String(rowData["plateNumber"]), PortailUrl: String(rowData["headerPath"]), MsgText: "我们成为了好友", FriendID: String(rowData["userID"]), FriendTopic: String(rowData["personTopic"])))
                            }
                            
                            self.FriendListTable!.reloadData()
                        }
                    }
                    
                }
        }
    }
    
    //跳转到聊天界面
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "privatechatdetail" {
            let indexPath = self.FriendListTable!.indexPathForSelectedRow
            let destinationViewController: FriendChat = segue.destinationViewController as! FriendChat
            
            //destinationViewController.FriendIDStr   = Friends[indexPath!.row].
            destinationViewController.PlatNumberStr = Friends[indexPath!.row].PlatNumberStr
            destinationViewController.FriendIDStr = Friends[indexPath!.row].FriendIDStr
            destinationViewController.FriendTopicStr = Friends[indexPath!.row].FriendTopicStr
            //destinationViewController.nameString = recipes[indexPath!.row].englishName
            //destinationViewController.channelIDInt = recipes[indexPath!.row].channelID
            //destinationViewController.channelTopic = recipes[indexPath!.row].channelTopic
            //destinationViewController.imageName = recipes[indexPath!.row].thumbnails
        }
        
    }
    
    
}